package com.hhp.hhptt.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.hhp.hhptt.common.Constants;
import com.hhp.hhptt.entity.User;
import com.hhp.hhptt.exception.ServiceException;
import com.hhp.hhptt.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



//@Component
public class JwtInterceptor implements HandlerInterceptor {
    private static final String TOKEN_SECRET = "my_secret_key";
    private static Logger logger = LoggerFactory.getLogger(JwtInterceptor.class);
    @Autowired
    UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String token = request.getHeader("token");
//        // 如果不是映射到方法直接通过
//        if (!(handler instanceof HandlerMethod)) {
//            return true;
//        }
//        if (StrUtil.isBlank(token)) {
//            throw new ServiceException(Constants.CODE_401, "无token，请登录");
//        }
//        String userId;
//        try {
//            userId = JWT.decode(token).getAudience().get(0);
//        } catch (JWTDecodeException e) {
//            throw new ServiceException(Constants.CODE_401, "token验证失败！");
//        }
//        User user = userService.getById(userId);
//        if (user == null) {
//            throw new ServiceException(Constants.CODE_401, "用户不存在！！");
//        }
//
//
//        // 验证 token,放置篡改等等
//        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
//        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
//        logger.info("token=="+token);
//
//        try {
//            jwtVerifier.verify(token);
//        } catch (JWTVerificationException e) {
//            logger.error("e==="+e.getMessage());
//            throw new ServiceException(Constants.CODE_401, "token验证失败！");
//
//        }
        return true;
    }
}
